package com.kly.manager.websocket;

import cn.hutool.core.util.StrUtil;
import com.kly.domain.entity.Picture;
import com.kly.domain.entity.User;
import com.kly.service.PictureService;
import com.kly.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author admin
 * @date 2025/3/21
 */
@Slf4j
@Configuration
public class WsCommentHandShakeInterceptor implements HandshakeInterceptor {

    @Resource
    private PictureService pictureService;

    @Resource
    private UserService userService;

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        // 强转位HttpServletRequest
        if(request instanceof ServletServerHttpRequest) {
            HttpServletRequest httpServletRequest = ((ServletServerHttpRequest) request).getServletRequest();
            // 获取pictureId 判断是那张图
            String pictureId = httpServletRequest.getParameter("pictureId");
            if (StrUtil.isBlank(pictureId)) {
                log.error("pictureId不能为空");
                return false;
            }
            // 判断图片是否存在
            Picture picture = pictureService.getById(pictureId);
            if (picture == null) {
                log.error("图片不存在");
                return false;
            }

        //     存储用户信息
            User loginUser = userService.getLoginUser(httpServletRequest);
            if (loginUser == null) {
                log.error("用户未登录");
                return false;
            }
            attributes.put("pictureId", Long.valueOf(pictureId));
            attributes.put("loginUser", loginUser);
        }

        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
